<template>
  <div class="app-container">
    <el-tabs v-model="storageStatus">
      <el-tab-pane label="待出库" name="wait"></el-tab-pane>
      <el-tab-pane label="已出库" name="out"></el-tab-pane>
    </el-tabs>

    <el-form
      ref="form"
      :inline="true"
      :model="formData"
      class="demo-form-inline"
    >
      <el-form-item>
        <el-input
          ref="searchInput"
          style="width: 500px"
          @keyup.enter.native="onSearch"
          v-model="formData.keywords"
          placeholder="手机号码、水洗码、物流单号、物流单号、水洗码"
        >
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-select v-model="formData.comeFrom" placeholder="请选择渠道">
          <el-option
            v-for="item in orderComeFromList"
            :label="item.label"
            :value="item.value"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-date-picker
          v-model="formData.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="订单开始日期"
          end-placeholder="订单结束日期"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>

        <el-button
          type="primary"
          @click="printOutStragePage"
          :loading="printLoading"
          >打印出库单</el-button
        >

        <el-button
          type="primary"
          @click="detail()"
          v-if="storageStatus === 'wait'"
          >批量出库</el-button
        >

        <el-button
          type="primary"
          @click="dialogVisible = true"
          v-if="storageStatus === 'wait'"
          >扫码出库</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      :data="list"
      v-loading="loading"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="orderNo" label="订单号" width="200">
      </el-table-column>
      <el-table-column prop="customPhone" label="手机号码" width="120">
      </el-table-column>
      <el-table-column label="渠道">
        <template slot-scope="scope">
          <el-tag type="success">{{
            orderComeFromMap[scope.row.comeFrom]
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="商品信息" prop="orderGoodsNames" width="200">
        <!-- <template slot-scope="scope">
          <div v-for="item in scope.row.orderGoodPoList">
            {{ productListMap[item.goodsId].name }}[{{
              productListMap[item.goodsId].price
            }}][{{ item.buyNum }}份]
          </div>
        </template> -->
      </el-table-column>

      <el-table-column
        prop="updateTime"
        label="更新时间"
        width="180"
      ></el-table-column>
      <el-table-column prop="shoeNum" label="鞋子数量" width="100">
        <template slot-scope="scope"> {{ scope.row.shoeNum }}双 </template>
      </el-table-column>
      <el-table-column label="门店名称">
        <template slot-scope="scope">
          {{
            shopListMap[scope.row.shopId]
              ? shopListMap[scope.row.shopId].shopName
              : "-"
          }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="240px" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="detail(scope.row.id)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      custom-class="order-create-dialog"
      :visible.sync="dialogVisible"
      style="z-index: 2013"
      append-to-body
      width="520px"
      title="扫码出库"
      center
    >
      <div>
        <el-input
          style="width: 480px"
          v-model="saomavalue"
          ref="input"
          @change="queryDetailByInput"
          placeholder="请输入订单号、水洗码、物流单号，或者扫描物流单号、水洗码"
        >
          <template slot="append">
            <el-button
              icon="el-icon-search"
              @click="queryDetailByInput"
            ></el-button>
          </template>
        </el-input>
      </div>
    </el-dialog>

    <pagination
      v-show="queryParams.total > 0"
      :total="queryParams.total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getListData"
    />

    <OutStorageDetail
      :drawerVisible="drawerVisible"
      :detailIds="detailIds"
      :shopListMap="shopListMap"
      :productListMap="productListMap"
      @close="detailClose"
      @goAhead="dialogVisible = true"
    />

    <PrintOutStrage
      :shopListMap="shopListMap"
      :productListMap="productListMap"
      :printOutStrageData="printOutStrageData"
      id="print-out-strage-list"
      ref="printOutStragePage"
    />
  </div>
</template>

<script>
import {
  getOrderList,
  getOutStorageLogList,
  getOrderDetail,
} from "@/api/order/index";
import { getShopGoods } from "@/api/product";
import {
  orderComeFromMap,
  orderComeFromList,
  orderStatusMap,
  orderStatusList,
} from "@/config";
import { getShopList } from "@/api/shop/index";
import OutStorageDetail from "./outStorageDetail";
import PrintOutStrage from "@/components/PrintOutStrage/PrintOutStrage";
import { setStartOfDay, setEndOfDay } from "@/utils/tool";
import { getOrderDetailByMulType } from "@/api/order/index";
export default {
  name: "Index",
  components: {
    OutStorageDetail,
    PrintOutStrage,
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      saomavalue: "",
      queryParams: {
        page: 1,
        limit: 10,
        pageSize:10,
        total: 0,
      },
      list: [],
      orderComeFromMap,
      orderStatusMap,
      orderComeFromList,
      orderStatusList,
      shopListMap: {},
      productListMap: {},

      formData: {
        comeFrom: "",
        keywords: "",
        dateRange: null,
      },

      storageStatus: "wait",

      multipleSelection: [],
      drawerVisible: false,
      detailIds: [],
      printOutStrageData: [],
      printLoading: false,
    };
  },
  mounted() {
    this.focusSearchInput();
  },
  created() {
    getShopGoods(
      {
        extendInfo: "abc",
      },
      1,
      999999
    ).then((res) => {
      let productListMap = {};
      res.data.records.forEach((item) => {
        productListMap[item.id] = item;
      });
      this.productListMap = productListMap;
    });
    getShopList({}, 1, 999999).then((res) => {
      let shopListMap = {};
      res.data.records.forEach((item) => {
        shopListMap[item.id] = item;
      });
      this.shopListMap = shopListMap;
    });

    this.getListData({
      page: 1,
      limit: 10,
    });
  },
  watch: {
    dialogVisible(val) {
      if (val === true) {
        this.$nextTick(() => {
          this.$refs.input.focus();
        });
      }
    },
    storageStatus() {
      this.formData = {
        comeFrom: "",
        keywords: "",
        dateRange: null,
      };
      this.queryParams = {
        page: 0,
        limit: 10,
        total: 0,
      };
      this.getListData({
        page: 1,
        limit: 10,
      });
    },
  },
  methods: {
    focusSearchInput() {
      this.$nextTick(() => {
        setTimeout(() => {
          if (this.$refs.searchInput) {
            this.$refs.searchInput.focus();
          }
        }, 300);
      });
    },
    getListData({ page, limit }) {
      this.loading = true;

      if (this.storageStatus === "wait") {
        const params = {
          comeFrom: this.queryParams.comeFrom,
          keywords: this.queryParams.keywords,
          status: 4,
          startTime: this.formData.dateRange
            ? setStartOfDay(this.formData.dateRange[0])
            : "",
          endTime: this.formData.dateRange
            ? setEndOfDay(this.formData.dateRange[1])
            : "",
        };
        getOrderList(params, page || this.queryParams.page + 1, this.queryParams.pageSize)
          .then(({ data }) => {
            this.list = data.records;
            this.queryParams.total = data.total;
            this.queryParams.page = data.current;
            this.queryParams.limit = data.size;
            this.queryParams.pageSize = data.size;
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        const params = {
          comeFrom: this.queryParams.comeFrom,
          searchString: this.queryParams.keywords,
          // 将选择的日期范围转换为开始时间和结束时间
          startTime: this.formData.dateRange
            ? setStartOfDay(this.formData.dateRange[0])
            : "",
          endTime: this.formData.dateRange
            ? setEndOfDay(this.formData.dateRange[1])
            : "",
        };
        getOutStorageLogList(params, page || this.queryParams.page + 1, this.queryParams.pageSize)
          .then(({ data }) => {
            this.list = data.records;
            this.queryParams.total = data.total;
            this.queryParams.page = data.current;
            this.queryParams.limit = data.size;
             this.queryParams.pageSize = data.size;
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
    detail(id) {
      if (id) {
        this.detailIds = [id];
        this.drawerVisible = true;
      } else {
        if (this.multipleSelection.length === 0) {
          this.$message.error("请选择订单");
          return;
        }
        this.detailIds = this.multipleSelection.map((item) => item.id);
        this.drawerVisible = true;
      }
    },
    onSearch() {
      // console.info("触发搜索")
      this.queryParams = {
        ...this.queryParams,
        ...this.formData,
      };
      this.getListData({
        page: 1,
        limit: 10,
      });
    },

    reset() {
      // console.log("reset");
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    printOutStragePage() {
      if (this.multipleSelection.length === 0) {
        this.$message.error("请选择订单");
        return;
      }
      this.printLoading = true;
      this.detailIds = this.multipleSelection.map((item) => item.id);
      const list = this.detailIds.map((id) => {
        return getOrderDetail(id);
      });
      Promise.all(list)
        .then((res) => {
          this.printOutStrageData = res.map((item) => item.data);
          this.$nextTick(() => {
            this.$refs.printOutStragePage.$refs.printBtn.click();
            setTimeout(() => {
              this.printOutStrageData = [];
            }, 500);
          });
        })
        .finally(() => {
          this.printLoading = false;
        });
    },
    detailClose() {
      this.drawerVisible = false;
      this.getListData(this.queryParams);
      this.focusSearchInput();
    },

    queryDetailByInput(e) {
      if (this.saomavalue) {
        getOrderDetailByMulType(this.saomavalue)
          .then((res) => {
            this.dialogVisible = false;
            this.saomavalue = "";
            this.detail(res.data.id);
          })
          .catch(() => {
            this.$message.error("未查询到订单信息");
          });
      } else {
        this.$message.error("请输入订单号、水洗码、物流单号");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.create {
  margin-bottom: 20px;
}
</style>
